jQuery.noConflict();

(function($, PLUGIN_ID) {

    'use strict';

    var conf = kintone.plugin.app.getConfig(PLUGIN_ID);
    var rowCount = Number(conf['rowCount']);

    $(document).ready(function() {
        var terms = {
            'ja': {
                'exchangeRate_text_title': '為替レート自動表示',
                'exchangeRate_text_row1': '関連AppID',
                'exchangeRate_text_row2': '決算日',
                'exchangeRate_text_column1': '通貨',
                'exchangeRate_text_column2': '為替レート',
                'exchangeRate_plugin_submit': '保存',
                'exchangeRate_plugin_cancel': 'キャンセル',
                'exchangeRate_error_message1': 'このアプリケーションは見つかりません。もう一度記入してください。',
                'exchangeRate_error_message2': 'フィールド名を選んでください。',
                'exchangeRate_error_message3': 'フィールド名を選んでください。',
                'exchangeRate_error_message4': '同じフィールド名を選ばないでください。'
            },
            'en': {
                'exchangeRate_text_title': 'Automatic Exchange Rate Display',
                'exchangeRate_text_row1': 'Related App ID',
                'exchangeRate_text_row2': 'Balance Date',
                'exchangeRate_text_column1': 'Currency',
                'exchangeRate_text_column2': 'Exchange Rate',
                'exchangeRate_plugin_submit': 'Save',
                'exchangeRate_plugin_cancel': 'Cancel',
                'exchangeRate_error_message1': 'This application is not found, please fill in again.',
                'exchangeRate_error_message2': 'Please select a field name.',
                'exchangeRate_error_message3': 'Please select a field name.',
                'exchangeRate_error_message4': 'Please do not select the same field name.'
            },
            'zh': {
                'exchangeRate_text_title': '自动显示汇率',
                'exchangeRate_text_row1': '关联AppID（汇率录入表ID）',
                'exchangeRate_text_row2': '结算日期字段（计算汇率的时间点）',
                'exchangeRate_text_column1': '币种选择字段',
                'exchangeRate_text_column2': '汇率显示字段',
                'exchangeRate_plugin_submit': '保存',
                'exchangeRate_plugin_cancel': '取消',
                'exchangeRate_error_message1': '无法找到此应用，请重新填写',
                'exchangeRate_error_message2': '请选择字段名称',
                'exchangeRate_error_message3': '请选择字段名称',
                'exchangeRate_error_message4': '请勿选择相同字段名称'
            }
        };

        // To switch the display by the login user's language (English display in the case of Chinese)
        var lang = kintone.getLoginUser().language;
        var i18n = (lang in terms) ? terms[lang] : terms['en'];
        var configHtml = $('#exchangeRate-plugin').html();
        var tmpl = $.templates(configHtml);
        $('div#exchangeRate-plugin').html(tmpl.render({'terms': i18n}));

        // escape fields vale
        function escapeHtml(htmlstr) {
            return htmlstr.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;')
                .replace(/"/g, '&quot;').replace(/'/g, '&#39;');
        }

        // set default
        function setDefault() {
            // Has been set up
            $('#relatedAppId').val(conf['relatedAppId']);
            $('#balanceDate').find('option[value=' + conf['balanceDate'] + ']').prop('selected', true);
            for (var i = 0; i < rowCount; i++) {
                var currency = conf['currency' + i];
                var exchangeRate = conf['exchangeRate' + i];
                $('#currency-' + i).find('option[value=' + currency + ']').prop('selected', true);
                $('#exchangeRate-' + i).find('option[value=' + exchangeRate + ']').prop('selected', true);
                // If only one line, hide the delete button
                if (rowCount > i + 1) {
                    var newTrNum = i + 1;
                    // Copy a line
                    $('#exchangeRateTableTr-0').clone(true).insertAfter($('tbody > tr').eq(newTrNum));
                    // Add ID to new line
                    $('tbody > tr').eq(newTrNum + 1).attr('id', 'exchangeRateTableTr-' + newTrNum);
                    var newRow = $('#exchangeRateTableTr-' + newTrNum);
                    // Add ID to each selection box
                    newRow.find('select:eq(0)').attr('id', 'currency-' + newTrNum);
                    newRow.find('select:eq(1)').attr('id', 'exchangeRate-' + newTrNum);
                    // Empty the new line
                    newRow.find('select').val('0');
                    newRow.find('span').css('display', 'none');
                }
            }

            if (rowCount > 1) {
                $('.kintoneplugin-button-remove-row-image').show();
            } else {
                $('.kintoneplugin-button-remove-row-image').hide();
            }
        }

        // set fields to selects
        var subTable;
        function setThisfields(resp) {
            for (var key in resp.properties) {
                if (!resp.properties.hasOwnProperty(key)) {continue;}
                var prop = resp.properties[key];
                var $option = $('<option>');
                $option.attr('value', escapeHtml(prop.code));
                $option.attr('name', escapeHtml(prop.type));
                if (prop.label) {
                    $option.text(escapeHtml(prop.label));
                }

                switch (prop.type) {
                    case 'DATE':
                        $('#balanceDate').append($option.clone());
                        break;
                    case 'SINGLE_LINE_TEXT':
                    case 'RADIO_BUTTON':
                    case 'DROP_DOWN':
                        $('#exchangeRateTable select:eq(0)').append($option.clone());
                        break;
                    case 'NUMBER':
                        $('#exchangeRateTable select:eq(1)').append($option.clone());
                        break;
                    case 'SUBTABLE':
                        subTable = prop.code;
                        for (var keyTable in prop.fields) {
                            var propTable = prop.fields[keyTable];
                            $option.attr('value', escapeHtml(propTable.code));
                            $option.attr('name', escapeHtml(propTable.type));
                            if (propTable.label) {
                                $option.text(escapeHtml(propTable.label));
                            }
                            switch (propTable.type) {
                                case 'SINGLE_LINE_TEXT':
                                case 'RADIO_BUTTON':
                                case 'DROP_DOWN':
                                    $('#exchangeRateTable select:eq(0)').append($option.clone());
                                    break;
                                case 'NUMBER':
                                    $('#exchangeRateTable select:eq(1)').append($option.clone());
                                    break;
                            }
                        }
                        break;
                    default:
                        break;
                }
            }
            setDefault();
        }

        // GET fields From this APP
        var url = kintone.api.url('/k/v1/preview/app/form/fields', true);
        var body = {
            app: kintone.app.getId()
        };
        kintone.api(url, 'GET', body, function(resp) {
            // success:
            setThisfields(resp);
        });

        // Add a line
        $('#exchangeRateTable').on('click', '.kintoneplugin-button-add-row-image', function() {
            rowCount = $('#exchangeRateTable').find('tr').length - 1;
            var maxTrNum = 0;
            $('tr[id^="exchangeRateTableTr-"]').each(function() {
                var trId = $(this).attr('id');
                var trNum = parseInt(trId.replace(/[^0-9]/ig, ''), 0);
                maxTrNum = trNum > maxTrNum ? trNum : maxTrNum;
            });
            var newTrNum = maxTrNum + 1;
            var thisTrId = $(this).parents('tr').attr('id');
            var newRow = $('#' + thisTrId).clone();
            newRow.attr('id', 'exchangeRateTableTr-' + newTrNum);
            newRow.find('select:eq(0)').attr('id', 'currency-' + newTrNum);
            newRow.find('select:eq(1)').attr('id', 'exchangeRate-' + newTrNum);
            newRow.find('select').val('-----');
            newRow.find('.exchangeRate-plugin-errormessage3, .exchangeRate-plugin-errormessage4')
                .css('display', 'none');
            $('#' + thisTrId).after(newRow);
            rowCount++;
            // More than 1 rows, display delete button
            if (rowCount > 1) {
                $('.kintoneplugin-button-remove-row-image').show();
            }
        });

        // Delete a line
        $('#exchangeRateTable').on('click', '.kintoneplugin-button-remove-row-image', function() {
            var thisTrId = $(this).parents('tr').attr('id');
            $('#' + thisTrId).remove();
            rowCount = $('#exchangeRateTable').find('tr').length - 1;
            // only one line,hide delete button 
            if (rowCount <= 1) {
                $('.kintoneplugin-button-remove-row-image').hide();
            }
        });

        // Line 1 Check 1:Not empty, numeric.
        var relatedAppIdError;
        $('#relatedAppId').blur(function() {
            relatedAppIdError = 0;
            var relatedAppId = $('#relatedAppId').val();
            if (!relatedAppId || isNaN(relatedAppId)) {
                $('.exchangeRate-plugin-checkright').css('display', 'none');
                $('.exchangeRate-plugin-errormessage1').css('display', 'inline-block');
                relatedAppIdError++;
            } else {
                var appUrl = kintone.api.url('/k/v1/preview/app/form/fields', true);
                var param = {
                    'app': relatedAppId
                };
                // Line 1 Check 2:Relevance success.
                kintone.api(appUrl, 'GET', param, function(resp) {
                    // success
                    var records = resp.properties;
                    if (!records.startDate || !records.endDate || !records.currency || !records.exchangeRate) {
                        $('.exchangeRate-plugin-checkright').css('display', 'none');
                        $('.exchangeRate-plugin-errormessage1').css('display', 'inline-block');
                        relatedAppIdError++;
                    } else {
                        $('.exchangeRate-plugin-checkright').css('display', 'inline-block');
                        $('.exchangeRate-plugin-errormessage1').css('display', 'none');
                    }
                }, function(error) {
                    // error
                    $('.exchangeRate-plugin-checkright').css('display', 'none');
                    $('.exchangeRate-plugin-errormessage1').css('display', 'inline-block');
                    relatedAppIdError++;
                });
            }
        });

        // Click "Save" to enter the settings
        $('#setting_submit').click(function() {
            $('.exchangeRate-plugin-errormessage2,' + ' .exchangeRate-plugin-errormessage3,'
             + ' .exchangeRate-plugin-errormessage4').css('display', 'none');
            var config = {};
            config['relatedAppId'] = $('#relatedAppId').val();
            config['balanceDate'] = $('#balanceDate').find('option:selected').val();
            config['subTable'] = subTable;
            rowCount = $('#exchangeRateTable').find('tr').length - 1;
            config['rowCount'] = String(rowCount);
            var maxTrNum = 0;
            $('tr[id^="exchangeRateTableTr-"]').each(function() {
                var trId = $(this).attr('id');
                var trNum = parseInt(trId.replace(/[^0-9]/ig, ''), 0);
                maxTrNum = trNum > maxTrNum ? trNum : maxTrNum;
            });
            // Find the contents of the settings
            var i = 0;
            for (var j = 0; j <= maxTrNum; j++) {
                if ($('#exchangeRateTableTr-' + j).length === 0) {
                    continue;
                } else {
                    config['currency' + i] = $('#currency-' + j).find('option:selected').val();
                    config['exchangeRate' + i] = $('#exchangeRate-' + j).find('option:selected').val();
                    i++;
                }
            }

            // Line 2 Check:Must be selected.
            var balanceDateError = 0;
            var balanceDate = config['balanceDate'];
            if (balanceDate === '-----') {
                $('#balanceDate').parent().parent().find('.exchangeRate-plugin-errormessage2')
                    .css('display', 'inline-block');
                balanceDateError++;
            }

            var emptyError = 0;
            var repeatError = 0;
            $('.kintoneplugin-table-td-control').each(function() {
                var thisTd = $(this);
                var thisSelected = thisTd.find('select option:selected').text();
                $('.kintoneplugin-table-td-control').each(function() {
                    var repeatSelected = $(this).find('select option:selected').text();
                    // Line 3 Table Check 1:1 and 2 columns must be selected.
                    if (thisSelected === '-----') {
                        thisTd.find('.exchangeRate-plugin-errormessage3,' +
                         ' .exchangeRate-plugin-errormessage3 span').css('display', 'inline-block');
                        emptyError++;
                    } else if (thisSelected === repeatSelected) {// Line 3 Table Check 2:Each value is unique.
                        if ($(this).find('select').eq(0).attr('id') !== thisTd.find('select').eq(0).attr('id')) {
                            thisTd.find('.exchangeRate-plugin-errormessage4,' +
                             ' .exchangeRate-plugin-errormessage4 span').css('display', 'inline-block');
                            repeatError++;
                        }
                    }
                });
            });
            if (relatedAppIdError > 0 || balanceDateError > 0 || emptyError > 0 || repeatError > 1) {
                return;
            }
            // Passing the settings to the application
            kintone.plugin.app.setConfig(config);
        });

        // Click "Cancel" to return to the previous page
        $('#setting_cancel').click(function() {
            if (window.confirm('Are you sure to cancel this setting?')) {
                history.back();
            } else {
                return;
            }
        });
    });

})(jQuery, kintone.$PLUGIN_ID);
